package org.sardine.beans;

import java.io.IOException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.apache.log4j.Logger;
import org.w3c.dom.Document;
import org.xml.sax.ErrorHandler;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;

public class DefaultDocumentLoader {
	
	private final Logger log = Logger.getLogger(DefaultDocumentLoader.class);
	private static final String SCHEMA_LANGUAGE_NAME = "http://java.sun.com/xml/jaxp/properties/schemaLanguage";
	private static final String SCHEMA_LANGUAGE_VALUE = "http://www.w3.org/2001/XMLSchema";
	
	public Document loadDocument(InputSource inputSource, ErrorHandler errorHandler, XmlValidationMode validationMode, boolean namespaceAware) throws ParserConfigurationException, SAXException, IOException {
		
		log.info("开始加载XML文档,验证类型为："+validationMode);
		DocumentBuilderFactory factory = createDocumentBuilderFactory(validationMode, namespaceAware);
		DocumentBuilder builder = createDocumentBuilder(factory, errorHandler);
		return builder.parse(inputSource);
	}
	
	protected DocumentBuilderFactory createDocumentBuilderFactory(XmlValidationMode valitationMode, boolean namespaceAware){
		
		DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
		factory.setValidating(true);
		factory.setNamespaceAware(namespaceAware);
		
		if(XmlValidationMode.XSD.equals(valitationMode)){
			factory.setAttribute(SCHEMA_LANGUAGE_NAME, SCHEMA_LANGUAGE_VALUE);
		}
		
		return factory;
	}
	
	protected DocumentBuilder createDocumentBuilder(DocumentBuilderFactory factory, ErrorHandler errorHandler) throws ParserConfigurationException{
		
		DocumentBuilder builder = factory.newDocumentBuilder();
		if(errorHandler != null){
			builder.setErrorHandler(errorHandler);
		}
		return builder;
		
	}

}
